#include "aichatwindow.h"
#include "ui_aichatwindow.h"
#include "publicstruct.h"
#include "mylistwidgetitem.h"
#include "mytcpsocket.h"
#include "customtextedit.h"

#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QJsonObject>

AIChatWindow::AIChatWindow(struct st_personData _userdata,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AIChatWindow)
{
    ui->setupUi(this);

    setQssStyle(QString("../style/AIChatWindow.qss"),this);

    this->setWindowTitle("AI聊天");

    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint);
    this->setMinimumSize(665,520);

    ai_head = QPixmap(":/prefix2/software/ai.png");
    QString uurl = QString("%1/%2.png").arg(PATH_IMG).arg(_userdata.dd_num);
    int borderWidth = 15; // 边框的宽度
    cv::Scalar borderColor(0, 0, 0, 255);
    user_head = RoundBorderPixmap(downLoadFromUrl(uurl),borderWidth,borderColor);

    //隐藏滚动条
    ui->listWidget_O->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //垂直滚动条
    ui->listWidget_O->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //水平滚动条

    QListWidgetItem* item = new QListWidgetItem(ui->listWidget_O);
    item->setSizeHint(QSize(ui->listWidget_O->width(),H_row));
    ui->listWidget_O->addItem(item);
    MyListWidgetItem* myitem = new MyListWidgetItem(
                QString("你好,我是一个AI,你可以和我聊天哦!"),R_FRIEND,ai_head,51,ui->listWidget_O->parentWidget());
    ui->listWidget_O->setItemWidget(item,myitem);


    // 绑定回车 发送按钮
    connect(ui->te_input,&CustomTextEdit::sendButtonPressed,ui->btn_send,&QPushButton::click);

}

AIChatWindow::~AIChatWindow()
{
    delete ui;
}

void AIChatWindow::addTextRecord(st_msg msg)
{
    QListWidgetItem* item = new QListWidgetItem(ui->listWidget_O);  //创建一个QListWidgetItem
    item->setSizeHint(QSize(ui->listWidget_O->width(),H_row));  //设置大小(主要是行高)
    ui->listWidget_O->addItem(item);    //加入ListWidget中
    MyListWidgetItem* myitem;
    if(msg.send == GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num){ //自己发的
        myitem = new MyListWidgetItem(msg.contect, R_USER,user_head,msg.type,ui->listWidget_O->parentWidget());
    }else{  //好友发的
        myitem = new MyListWidgetItem(msg.contect, R_FRIEND,ai_head,msg.type,ui->listWidget_O->parentWidget());
    }
    myitem->seq = autoSeq++;  //记录下位置
    ui->listWidget_O->setItemWidget(item,myitem);   //用自定义Widget填充刚才创建的ListWidgetItem
    // 文本宽度超出最大限制,更新QListWidgetItem的高度
    connect(myitem,SIGNAL(sig_rectChange(QSize,int)),this,SLOT(updateItemSize(QSize,int)));

    // 滚动到底部
    ui->listWidget_O->scrollToBottom();
}

void AIChatWindow::updateItemSize(QSize size, int index)
{
    //更新对应Item的高
    ui->listWidget_O->item(index)->setSizeHint(size);
    update();
}

void AIChatWindow::slot_replyfinish(QNetworkReply *reply)
{
    QString answer;
    QString data = reply->readAll();
    qDebug()<<"这是返回的结果 "+data;
        QJsonParseError json_error;
        //一定要toUtf8 否则会出错！
        QJsonDocument json=QJsonDocument::fromJson(data.toUtf8(),&json_error);
        //判断有没有错
        if(json_error.error==QJsonParseError::NoError)
        {
            if(json.isObject())
            {
                QJsonObject jsonObj=json.object();
                //取到text内容
                if(jsonObj.contains("content"))
                {
                    qDebug()<<"成功获取text";
                    QJsonValue text_value=jsonObj.take("content");
                    if(text_value.isString())
                    {
                        answer=text_value.toVariant().toString();
                        answer.replace("br","\n");
                        //qDebug()<<"!!!返回的ans:"<<answer;
                        struct st_msg msg;
                        msg.send = 007;
                        msg.recv = GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num; // 表示AI
                        msg.contect = answer;
                        msg.type = 51;  // 私聊文本
                        msg.sendtime = "刚刚";

                        addTextRecord(msg);

                    }
                }
            }
        }
        reply->deleteLater();
}

void AIChatWindow::on_btn_send_clicked()
{
    QString text = ui->te_input->toPlainText();   //用户输入的内容
    if(text.isEmpty())
       return;

    QString str = QString("http://api.qingyunke.com/api.php?key=free&appid=0&msg=%1").arg(text);
    QUrl url(str);
    QNetworkRequest request(url);
    QNetworkAccessManager* manager = new QNetworkAccessManager(this);
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slot_replyfinish(QNetworkReply*)));
    manager->get(request);  //发布一个请求以获取目标请求的内容,新数据到达时,触发readyRead()信号
    ui->te_input->clear();

    struct st_msg msg;
    msg.send = GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num;
    msg.recv = 007; // 表示AI
    msg.contect = text;
    msg.type = 51;  // 私聊文本
    msg.sendtime = "刚刚";

    addTextRecord(msg);

}

